import 'dart:async';

import 'package:flutter/cupertino.dart';

import '../style/common_color.dart';

//倒计时viwe
class DownTextView extends StatefulWidget {
  final String title;
  final int time;
  final Function? startCallback;
  final VoidCallback? endCallback;
  const DownTextView(this.title,{Key? key,this.time = 60,this.startCallback, this.endCallback}) : super(key: key);

  @override
  _DownTextViewState createState() => _DownTextViewState();
}

class _DownTextViewState extends State<DownTextView> {
  bool _isDown = false;//是否在倒计时
  Timer? _timer;
  int _curentTimer = 0;
  String _text = "";
  Color _textColor = themeColor;
  @override
  void initState() {
    _curentTimer = widget.time;
    _text = widget.title;
    super.initState();
  }

  @override
  void dispose() {
    ///取消计时器
    _timer?.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      width: 80,
      child: GestureDetector(

        onTap: (){
          bool success = widget.startCallback!();
          if(!_isDown&&success){
            //开始倒计时
            _isDown = true;
            _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
              ///定时任务
              if(_curentTimer<=1){
                _timer?.cancel();
                _timer = null;
                _isDown = false;
                setState(() {
                  _text = "重新获取";
                  _curentTimer = widget.time;
                  _textColor = themeColor;
                });
              }else{
                setState(() {
                  _text = "$_curentTimer秒";
                  _textColor = color_999;
                });
                _curentTimer--;
              }
            });
          }
        },
        child: Text(_text,style: TextStyle(color: _textColor,fontSize: 16)),
      )
    );
  }
}
